package br.slic.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import br.slic.entidade.EntidadePersistente;
import br.slic.exception.ServiceException;
import br.slic.services.interfaces.GenericServiceLocal;

public abstract class GenericConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext facesContext, UIComponent ui, String str) {
		Object obj = null;
		try {
			Long id = Long.parseLong(str);
			obj = getService().obterEntidade(id, getClazz());
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		return obj;
	}

	@Override
	public String getAsString(FacesContext facesContext, UIComponent ui, Object obj) {
		String retorno = obj.toString();
		if( obj instanceof EntidadePersistente ) {
			retorno = ((EntidadePersistente)obj).getId().toString();
		}
		return retorno;
	}	
	
	protected abstract GenericServiceLocal getService();
	
	@SuppressWarnings("rawtypes")
	protected abstract Class getClazz();
	
}
